package com.zzt.zt_trasact;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 输入法遮住输入框的问题 是fitsSystemWindows造成的
 * android:fitsSystemWindows="false"
 * 使用了SystemBarTintManager 造成的影响
 * 去掉就ok了
 * 然后 EditText 设置了 android:background=""属性也会遮住输入框
 */

@SuppressLint("NewApi")
//public abstract class BaseActivity extends FragmentActivity {
public abstract class BaseActivity extends AppCompatActivity {
    private String TAG = "BaseActivity";
    public static final String SUCCESS = "SUCCESS";
    public static final String ERROR = "ERROR";
    public static final String FAIL = "FAIL";
    public static LinkedList<Activity> sAllActivitys = new LinkedList<Activity>();

    //系统导航栏的颜色
    int statusBarRes = R.color.red;
    // app是否在前台
    public boolean isForeground = false;

    //充值完成验证姓名是否一致，电子钱包图片上传 true:显示弹框，false:不显示弹框
    public static boolean paypalAuthDialog;
    public static boolean isShowPaypalAuthDialog;

    // 是否网页打开
    protected boolean isHtmlApp = false;


    public static Activity getTopActivity() {
        if (sAllActivitys.isEmpty())
            return null;
        return sAllActivitys.getLast();
    }


    @Override
    public void finish() {
        sAllActivitys.remove(this);
        super.finish();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        sAllActivitys.add(this);
        super.onCreate(savedInstanceState);
        // 启动的时候 app在前台
        isForeground = true;
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        if (Build.VERSION.SDK_INT >= 21) {
            updateStatusBarColor(getResources().getColor(getStatusBarTintResource()));
        } else {
            configSystemBar();
        }
        statusBar();
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        if (Build.VERSION.SDK_INT >= 21) {
            updateStatusBarColor(getResources().getColor(getStatusBarTintResource()));
        } else {
            configSystemBar();
        }
        statusBar();
    }

    public void setContentView2(int layoutResID) {
//        super.setContentView(layoutResID);
//        backListener();
//        ViewGroup view = findViewById(android.R.id.content);
//        ViewGroup parent = (ViewGroup) view.getParent();
//        ViewGroup.LayoutParams params = parent.getLayoutParams();
//        final ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
//        decorView.removeAllViews();
//        parent.removeAllViews();
//        parent = new ContentRootView(this);
//        parent.setFitsSystemWindows(true);
//        parent.setClipToPadding(false);
//        parent.addView(view, -1, -1);
//        decorView.addView(parent, params);
//        parent.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
//            for (int i = 1; i < decorView.getChildCount(); i++)
//                decorView.getChildAt(i).setVisibility(View.GONE);
//        });
        setContentView2(layoutResID, true);
    }

    public void setContentView2(int layoutResID, boolean isChangeStatusBar) {
        super.setContentView(layoutResID);
        ViewGroup view = findViewById(android.R.id.content);
        // 选移除父布局
        ViewGroup viewParent = (ViewGroup) view.getParent();
        viewParent.removeAllViews();
//        ViewGroup.LayoutParams params = parent.getLayoutParams();
        final ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
        // 查找新的根布局
        ViewGroup parent = (ViewGroup) decorView.getChildAt(0);
        ViewGroup.LayoutParams params = parent.getLayoutParams();

        decorView.removeAllViews();
        parent.removeAllViews();
        parent = new ContentRootView(this);
        parent.setFitsSystemWindows(true);
        parent.setClipToPadding(false);
        parent.addView(view, -1, -1);
        decorView.addView(parent, params);
        parent.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
            for (int i = 1; i < decorView.getChildCount(); i++)
                decorView.getChildAt(i).setVisibility(View.GONE);
        });


        if (isChangeStatusBar) {
            statusBar();
        }
        setBarHeight();
    }

    /**
     * 设置状态栏高度
     */
    private void setBarHeight() {

    }

    public void setContentView2(View layoutView) {
        setContentView2(layoutView, true);
    }

    public void setContentView2(View layoutView, boolean isChangeStatusBar) {
        super.setContentView(layoutView);
        ViewGroup view = findViewById(android.R.id.content);
        // 先移除父布局
        ViewGroup viewParent = (ViewGroup) view.getParent();
        viewParent.removeAllViews();
//        ViewGroup.LayoutParams params = parent.getLayoutParams();
        final ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
        // 查找新的根布局
        ViewGroup parent = (ViewGroup) decorView.getChildAt(0);
        ViewGroup.LayoutParams params = parent.getLayoutParams();

        decorView.removeAllViews();
        parent.removeAllViews();
        parent = new ContentRootView(this);
        parent.setFitsSystemWindows(true);
        parent.setClipToPadding(false);
        parent.addView(view, -1, -1);
        decorView.addView(parent, params);
        parent.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
            for (int i = 1; i < decorView.getChildCount(); i++)
                decorView.getChildAt(i).setVisibility(View.GONE);
        });
        if (isChangeStatusBar) {
            statusBar();
        }
        setBarHeight();


    }


    public void statusBar() {
        //新的状态栏样式
        StatusBarUtil.setWindowStatusBarColor(this, getStatusBarTintResource());
        StatusBarUtil.statusBarLightMode(this);
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return WidgetUtil.onCreateView(super.onCreateView(name, context, attrs), name, context, attrs);
    }


    public boolean isActivityFitsSystemWindows() {
        return true;
    }

    public void configSystemBar() {
        try {
            if (!isActivityFitsSystemWindows())
                return;

            //fitsSystemWindows是否修改状态栏的总开关   使用style 达不到效果，只能在xml布局中使用fitsSystemWindows属性
            boolean flag = getResources().getBoolean(R.bool.fitsSystemWindows);
            if (!flag)
                return;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                setTranslucentStatus(true);
            }

            statusBarTintResource();


        } catch (Exception e) {
            e.printStackTrace();
        } catch (Error e) {
            e.printStackTrace();
        }
    }

    /**
     * 状态栏颜色 或者图片
     *
     * @return
     */
    public int getStatusBarTintResource() {
        return statusBarRes;
    }

    public void setStatusBarTintResource(int res) {
        statusBarRes = res;
    }

    /**
     * Override this method to setStatusBarTintResource
     */
    public void statusBarTintResource() {
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(getStatusBarTintResource());
    }

    /**
     * for systemBar
     *
     * @param on
     */
    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    protected void appCommonGoBack() {
        doMyfinish();
    }

    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }


    @Override
    public void onDestroy() {
        sAllActivitys.remove(this);
        super.onDestroy();
    }

    private boolean isResumed;
    private List<Runnable> resumedTasks = new ArrayList<>();

    public void enqueue(Runnable runnable) {
        if (isResumed)
            runnable.run();
        else
            resumedTasks.add(runnable);
    }

    public void doMyfinish() {

        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            doMyfinish();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 更新StatusBar颜色
     *
     * @param color
     */
    public void updateStatusBarColor(int color) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(color);
    }

//	private boolean isTopActivity(Activity activity) {
//		ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
//		return cn.getClassName().contains(activity.getClass().getName());
//	}


    @Override
    public void startActivity(Intent intent) {
        if (intent == null) {
            return;
        }

        super.startActivity(intent);
    }


    private boolean isAttachedToWindow;

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        isAttachedToWindow = true;
    }

    public boolean isAttachedToWindow() {
        return isAttachedToWindow;
    }


}
